package com.controller;

import com.pojo.Result;
import com.pojo.Users;
import com.service.UserService;
import com.utils.JwtUtil;
import com.utils.RedisUtil;
import com.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final RedisUtil redisUtil;

    @Autowired
    public UserController(UserService userService, JwtUtil jwtUtil, RedisUtil redisUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
        this.redisUtil = redisUtil;
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @PostMapping("/register")
    public Result<Users> register(@RequestBody Users user) {
        return userService.register(user);
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        Result<Users> userResult = userService.login(loginRequest.getUsername(), loginRequest.getPassword());

        if (userResult.getCode() != 200 || userResult.getData() == null) {
            return Result.error(userResult.getCode(), userResult.getMsg());
        }

        Users user = userResult.getData();
        Long userId = Long.valueOf(user.getId());

        // 生成Token
        String token = jwtUtil.generateToken(user.getUsername(), userId);

        // 获取Token过期时间（毫秒）
        long expirationMillis = jwtUtil.getExpirationMillis();

        // 存储用户ID与Token的绑定关系（使用正确的过期时间）
        redisUtil.setUserToken(userId, token, expirationMillis);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        result.put("expiresIn", expirationMillis / 1000); // 返回秒数

        return Result.success(result);
    }

    @PostMapping("/refresh")
    public Result<Map<String, Object>> refreshToken(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "缺少有效的Authorization头");
        }

        String token = authHeader.substring(7);

        // 验证Token是否有效
        if (!jwtUtil.validateToken(token)) {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "无效的Token");
        }

        // 获取用户信息
        String username = jwtUtil.getUsernameFromToken(token);
        Long userId = jwtUtil.getUserIdFromToken(token);

        // 检查Redis中该用户当前的Token
        String currentValidToken = redisUtil.getUserToken(userId);
        if (currentValidToken == null || !currentValidToken.equals(token)) {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "Token已失效或在其他设备登录");
        }

        // 生成新Token
        String newToken = jwtUtil.generateToken(username, userId);
        long expirationMillis = jwtUtil.getExpirationMillis();

        // 更新Redis中的Token
        redisUtil.setUserToken(userId, newToken, expirationMillis);

        Map<String, Object> result = new HashMap<>();
        result.put("token", newToken);
        result.put("expiresIn", expirationMillis / 1000); // 返回秒数

        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<Users> getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PutMapping("/{id}")
    public Result<Void> updateUser(@PathVariable Long id, @RequestBody Users user) {
        user.setId(Math.toIntExact(id));
        return userService.updateUser(user);
    }

    @PatchMapping("/{id}/avatar")
    public Result<Void> updateAvatar(@PathVariable Long id, @RequestBody String avatarUrl) {
        return userService.updateAvatar(id, avatarUrl);
    }

    @PatchMapping("/{id}/password")
    public Result<Void> updatePassword(@PathVariable Long id, @RequestBody PasswordRequest passwordRequest) {
        return userService.updatePassword(id, passwordRequest.getOldPassword(), passwordRequest.getNewPassword());
    }

    @PatchMapping("/{id}/bio")
    public Result<Void> updateBio(@PathVariable Long id, @RequestBody String bio) {
        return userService.updateBio(id, bio);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }

    @GetMapping
    public Result<List<Users>> getAllUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return userService.getAllUsers(page, size);
    }

    @GetMapping("/check-username")
    public Result<Boolean> checkUsernameAvailable(@RequestParam String username) {
        return userService.checkUsernameAvailable(username);
    }

    @GetMapping("/check-email")
    public Result<Boolean> checkEmailAvailable(@RequestParam String email) {
        return userService.checkEmailAvailable(email);
    }

    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "缺少有效的Authorization头");
        }

        String token = authHeader.substring(7);

        try {
            // 获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);

            // 清除Redis中的Token绑定
            redisUtil.removeUserToken(userId);

            return Result.success();
        } catch (Exception e) {
            // 即使Token无效也返回成功
            return Result.success();
        }
    }


    @PostMapping("/login-by-code/{email}/{code}")
    public Result<String> loginByCode(
            @PathVariable String email,
            @PathVariable String code) {

        // 原有登录逻辑保持不变
        String redisKey = "code:" + email;
        System.out.println("登录时读取Redis的Key：" + redisKey);
        String serverCode = (String) redisTemplate.opsForValue().get(redisKey);
        System.out.println("从Redis读取的验证码：" + serverCode);
        System.out.println("用户输入的验证码：" + code);

        if (serverCode == null) {
            return Result.error("验证码已过期!");
        }
        if (!serverCode.equals(code)) {
            return Result.error("验证码错误!");
        }
        Users user = userService.getByEmail(email);
        if (user == null) {
            return Result.error("用户不存在!");
        }
        String token = jwtUtil.generateToken(user.getUsername(), Long.valueOf(user.getId()));
        return Result.success(token);
    }


    @GetMapping("/by-email")
    public Result<Users> getUserByEmail(@RequestParam String email) {

        Users user = userService.getByEmail(email);

        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error(HttpStatus.NOT_FOUND.value(), "用户不存在");
        }
    }


    static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

    static class PasswordRequest {
        private String oldPassword;
        private String newPassword;

        public String getOldPassword() {
            return oldPassword;
        }

        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}